package com.demo.my.Util;

import lombok.extern.java.Log;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")

@Log
public class AuthorizeFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String requestURI = req.getRequestURI();
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        if(requestURI.contains("/css")||requestURI.contains("/js/")||
                requestURI.contains("/jsp/login.jsp")||requestURI.contains("/img")||requestURI.contains("/fonts")||requestURI.contains("/dist")||
                requestURI.contains("/login")||requestURI.equals("/")||requestURI.contains("/favicon.ico")){
            log.info("进入Authorize过滤器：没有被过滤的url:"+requestURI);
            filterChain.doFilter(req,servletResponse);
            return;
        }else {
            Object user_info = req.getSession().getAttribute("user_info");
            if(user_info!=null){
                log.info("进入Authorize过滤器：未登录没有被过滤的u没有被过滤的:"+requestURI);
                filterChain.doFilter(req,servletResponse);
                return;
            }else{
                log.info("进入Authorize过滤器：未登录被过滤的url:"+requestURI);
                servletResponse.setContentType("text/html;charset=utf-8");
                servletResponse.getWriter().write("<script type=\"text/javascript\">\n" +
                        "\talert(\"未登录，回到登录页面\")\n" +
                        "\tsetTimeout(function () {\n" +
                        "\t\twindow.location.href = \"/jsp/login.jsp\";\n" +
                        "    },500)\n" +
                        "</script>");
                return;
            }
        }
    }

    @Override
    public void destroy() {

    }
}
